from django.db import models
from django.contrib.auth.models import (
    BaseUserManager, AbstractBaseUser,PermissionsMixin
)
class MyUserManager(BaseUserManager):
    def create_user(self, email,name, password=None):
        """
        Creates and saves a User with the given email, date of
        birth and password.
        """
        if not email:
            raise ValueError('Users must have an email address')

        user = self.model(
            email=self.normalize_email(email),
            name=name,
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email,name, password):
        """
        Creates and saves a superuser with the given email, date of
        birth and password.
        """
        user = self.create_user(
            email,
            password=password,
            name=name,
        )
        user.is_superuser=True
        user.is_admin=True
        user.save(using=self._db)
        return user


class UserProfile(AbstractBaseUser,PermissionsMixin):
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
        null=True,
        blank=True
    )
    name = models.CharField(max_length=64,verbose_name="姓名",blank=True,null=True)
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False) #是否可以登录后台管理界面
    is_superuser = models.BooleanField(default=False)
    phone=models.CharField(max_length=20)

    objects = MyUserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['name']

    def get_full_name(self):
        # The user is identified by their email address
        return self.email

    def get_short_name(self):
        # The user is identified by their email address
        return self.name

    def __str__(self):              # __unicode__ on Python 2
        return self.email

    @property
    def is_staff(self):
        "Is the user a member of staff?"
        # Simplest possible answer: All admins are staff
        return self.is_admin
    class Meta:
        permissions=(
            ('crm_table_obj_list','查看客户列表'),
            ('crm_table_obj_change','修改客户信息'),
            ('crm_table_obj_view','查看客户信息修改页'),
        )


class Idc(models.Model):
    name=models.CharField(max_length=255,unique=True)
    position=models.CharField(max_length=255)
    def __str__(self):
        return self.name

class Tag(models.Model):
    name=models.CharField(max_length=50,unique=True)
    def __str__(self):
        return self.name

class BusinessUnit(models.Model):
    name=models.CharField(max_length=128,unique=True)
    administrator_name=models.CharField(max_length=128)
    administrator_phone=models.CharField(max_length=20)
    def __str__(self):
        return self.name

class Asset(models.Model):
    type=models.CharField(default='服务器',max_length=10)

    idc=models.ForeignKey('Idc',on_delete=models.PROTECT)
    tag=models.ForeignKey('Tag',null=True,blank=True,on_delete=models.PROTECT)
    businessunit=models.ForeignKey('BusinessUnit',null=True,blank=True,on_delete=models.PROTECT)
    cabinet_order=models.CharField('机柜号',max_length=128,unique=True)
    update_time=models.DateTimeField(auto_now=True,verbose_name='更新时间')
    report_time=models.DateTimeField('最近一次汇报资产信息时间',auto_now=True)
    create_time=models.DateTimeField(auto_now_add=True)
    server=models.OneToOneField('Server',related_name='Rserver',null=False,blank=False)

    def __str__(self):
        return '%s--%s'%(self.type,self.cabinet_order)

class Asset_status(models.Model):
    """
    资产状态表，用于展示报表
    """
    status=(
        (0,'正常'),
        (1,'离线'),
        (2,'变更'),
        (3,'硬件丢失'),
        (4,'错误')
    )
    physical_type=(
        (0,'cpu'),
        (1,'disk'),
        (2,'mem'),
        (3,'nic'),
        (4,'server'),
    )
    action_type=(
        (0,'变更'),
        (1,'丢失')
    )#判断相应的动作，决定前端是否显示'删除硬件'按钮
    action=models.PositiveIntegerField(choices=action_type,null=True,blank=True)
    type=models.PositiveIntegerField('硬件类型',choices=physical_type,null=True,blank=True)
    r_id=models.IntegerField('关联硬件的ID',null=True,blank=True)
    asset_status=models.PositiveIntegerField(choices=status,default=0,)
    asset=models.ForeignKey('Asset',null=True) #null=True,薪资产上报出现错误的时候可以存放错误信息，第一次上报还不属于任何资产，所以设置null=True
    content=models.CharField(max_length=254,null=True,blank=True)
    update_time=models.DateTimeField(auto_now=True)
    def __str__(self):
        return '%s--%s'%(self.action,self.type)
class Discard_server(models.Model):
    hostname = models.CharField(max_length=128)
    sn = models.CharField('SN号', max_length=64, db_index=True)
    manufacturer = models.CharField(verbose_name='制造商', max_length=64, null=True, blank=True)
    model = models.CharField('型号', max_length=64, null=True, blank=True)
    manage_ipv4 = models.CharField('管理IPv4', null=True, blank=True,max_length=64)
    manage_ipv6 = models.CharField('管理IPv6', null=True, blank=True,max_length=128)
    os_platform = models.CharField('系统', max_length=16, null=True, blank=True)
    os_version = models.CharField('系统版本', max_length=64, null=True, blank=True)
    cpu_count = models.IntegerField('CPU个数', null=True, blank=True)
    cpu_physical_count = models.IntegerField('CPU物理个数', null=True, blank=True)
    cpu_model = models.CharField('CPU型号', max_length=128, null=True, blank=True)
    create_at = models.DateTimeField(auto_now_add=True, blank=True)
    def __str__(self):
        return self.hostname

class Server(models.Model):
    asset = models.OneToOneField('Asset',null=True,blank=True,related_name='Server')
    hostname = models.CharField(max_length=128)
    sn = models.CharField('SN号', max_length=64, db_index=True)
    manufacturer = models.CharField(verbose_name='制造商', max_length=64, null=True, blank=True)
    model = models.CharField('型号', max_length=64, null=True, blank=True)
    manage_ipv4 = models.CharField('管理IPv4', null=True, blank=True,max_length=64)
    manage_ipv6 = models.CharField('管理IPv6', null=True, blank=True,max_length=128)
    os_platform = models.CharField('系统', max_length=16, null=True, blank=True)
    os_version = models.CharField('系统版本', max_length=64, null=True, blank=True)
    cpu_count = models.IntegerField('CPU个数', null=True, blank=True)
    cpu_physical_count = models.IntegerField('CPU物理个数', null=True, blank=True)
    cpu_model = models.CharField('CPU型号', max_length=128, null=True, blank=True)
    create_at = models.DateTimeField(auto_now_add=True, blank=True)
    update_time=models.DateTimeField(auto_now=True)
    def __str__(self):
        return self.hostname

class Disk(models.Model):
    name=models.CharField(max_length=128)
    size=models.CharField(max_length=64)
    server=models.ForeignKey('Server')
    update_time=models.DateTimeField(auto_now=True)
    def __str__(self):
        return '%s -- %s'%(self.name,self.size)

class Memory(models.Model):
    size=models.CharField(max_length=64)
    speed=models.CharField(max_length=64)
    sn=models.CharField(max_length=64)
    server=models.ForeignKey('Server')
    update_time=models.DateTimeField(auto_now=True)
    def __str__(self):
        return '%s-%s'%(self.size,self.speed)

class Nic(models.Model):
    name=models.CharField(max_length=128)
    mac=models.CharField(max_length=64)
    speed=models.CharField(max_length=64)
    server=models.ForeignKey('Server')
    update_time=models.DateTimeField(auto_now=True)
    def __str__(self):
        return self.name

class asset_change_log(models.Model):
    """
    资产变更记录，主要记录客户端汇报时与CMDB数据库中存在的差异
    """
    server=models.ForeignKey('Server')
    level=(
        (0,'一般'),
        (1,'严重')
    )
    log_level=models.IntegerField(choices=level,)
    change_detail=models.CharField('变更内容',max_length=255,blank=False,null=False)
    change_date=models.DateTimeField(auto_now=True,editable=False)

class Audit_log(models.Model):
    user=models.ForeignKey(UserProfile)
    date=models.DateTimeField(auto_now=True)
    content=models.CharField(max_length=255)

class Notepad(models.Model):
    user=models.ForeignKey(UserProfile)
    date=models.DateTimeField(auto_now=True)
    title=models.CharField(max_length=128)
    content=models.CharField(max_length=255)